#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class HenanSanmenxiaPolicy(BaseTaxPolicySpider):
    name = 'henan_sanmenxia_policy'
    
    province = '河南省'
    city = '三门峡市'
    # county = '滑县'
    park = ''

    def start_requests(self):
        for source, county, url in [
            ['三门峡市湖滨区人民政府', "湖滨区", "https://www.hubin.gov.cn/pageView/zhengfuxinxi.html?lmid=25179&rlmid=25108"],
            ['三门峡市湖滨区人力资源和社会保障局', "湖滨区", "https://www.hubin.gov.cn/pageView/subList.html?lmid=25317&rlmid=25245"],
            ['三门峡市湖滨区农业农村局', "湖滨区", "https://www.hubin.gov.cn/pageView/subList.html?lmid=25299&rlmid=25242"],
            ['三门峡市灵宝市人民政府', "灵宝市", "https://www.lingbao.gov.cn/pageView/xzfilesList.html?searchType=1"],
            ['三门峡市卢氏县人民政府', "卢氏县", "https://www.lushixian.gov.cn/pageView/xzfilesList.html?searchType=1"],
            ['三门峡市渑池县人民政府', "渑池县", "https://www.mianchi.gov.cn/pageView/zhengfuxinxi.html?lmid=23530&rlmid=23322"],
            ['三门峡市陕州区人民政府', "陕州区", "https://www.shanzhou.gov.cn/pageView/xzfilesList.html?searchType=1"],
            ['三门峡市发展和改革委员会', "", "http://fgw.smx.gov.cn/pageView/xzfilesList.html?searchType=1"],
            ['三门峡市工业和信息化局', "", "http://gxj.smx.gov.cn/pageView/xzfilesList.html?searchType=1"],
            ['三门峡市科学技术局', "", "http://kjj.smx.gov.cn/pageView/xzfilesList.html?searchType=1"],
            ['三门峡市人力资源和社会保障局', "", "http://rsj.smx.gov.cn/pageView/xzfilesList.html?searchType=1"],
            ['三门峡市住房和城乡建设局', "", "http://zjj.smx.gov.cn/pageView/xzfilesList.html?searchType=1"],
            ['三门峡市农业农村局', "", "http://nyncj.smx.gov.cn/pageView/xzfilesList.html?searchType=1"],
            ['三门峡市商务局', "", "http://swj.smx.gov.cn/pageView/xzfilesList.html?searchType=1"],
            ['三门峡市市场监督管理局', "", "http://scjg.smx.gov.cn/pageView/xzfilesList.html?searchType=1"],
            ['三门峡市财政局', "", "http://czj.smx.gov.cn/pageView/xzfilesList.html?searchType=1"],
        ]:
            params = dict(urllib.parse.parse_qsl(urllib.parse.urlparse(url).query))
            item = {'source': source, 'county': county}
            url = url.split("?")[0]
            yield scrapy.Request(url + '?' + urllib.parse.urlencode(params), callback=self.parse_list, meta={'item': item, "params": params, "url": url}, dont_filter=True)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.xpath(
            "//div[@class='page_list' or @class='article-list' or @class='bd']//li//a[(contains(@href, '.htm') or @title)]/ancestor::li[string-length(string(.))>=10] | "
            "//ul[contains(@class, 'ul ULLIST')]//li//a[(contains(@href, '.htm') or @title)]/ancestor::li[string-length(string(.))>=10]"
        ):
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").get()
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
            #     continue
            if '.htm' not in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total = response.xpath(""".""").re_first(r"const\s*total\s*=\s*'(\d+)'") or response.xpath(""".""").re_first(r"共(\d+)篇")
            pageSize = response.xpath(""".""").re_first(r"const\s*pageSize\s*=\s*'(\d+)'") or response.xpath(""".""").re_first(r"(\d+)篇/页")
            totalpage = math.ceil(int(total) / int(pageSize))
            params = response.meta.get('params')
            print(response.url, 'page:', totalpage)
            for page in range(1, int(totalpage) + 1):
                url = response.url.split("?")[0]
                params['pageNum'] = page
                yield response.follow(url + '?' + urllib.parse.urlencode(params), callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("//*[contains(.//text(), '发布日期：') or contains(.//text(), '发布时间：')]//text()").re_first(r"(\d{4}-\d{1,2}-\d{1,2})")
        # print(item['publish_date'])
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl henan_sanmenxia_policy".split())
